package a05_双指针法;

/**
 * <p>
 * a07_链表相交
 * </p>
 *
 * @author flyduck
 * @since 2024-07-23
 */
public class a07_链表相交复习2 {
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //计算长度
        int lengthA = 0;
        ListNode currentA = headA;
        while (currentA != null){
            currentA = currentA.next;
            lengthA++;
        }

        int lengthB = 0;
        ListNode currentB = headB;
        while (currentB != null){
            currentB = currentB.next;
            lengthB++;
        }

        //长的先走
        currentA = headA;
        currentB = headB;
        if(lengthA > lengthB){
            int differLength = lengthA - lengthB;
            while (differLength > 0) {
                currentA = currentA.next;
                differLength--;
            }
        }else if(lengthB > lengthA){
            int differLength = lengthB - lengthA;
            while (differLength > 0) {
                currentB = currentB.next;
                differLength--;
            }
        }

        //一起走
        while (currentA != null && currentB != null) {
            if(currentA == currentB){
                return currentA;
            }
            currentA = currentA.next;
            currentB = currentB.next;
        }
        return null;
    }

    public static void main(String[] args) {
        ListNode headA = new ListNode(1);

        ListNode headB = headA;

        System.out.println(getIntersectionNode(headA, headB));
    }
}
